import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { useDispatch } from "react-redux";

export type IndexStateType = {
  from: string;
  to: string;
  isCitySelectorVisible: boolean;
  currentSelectingLeftCity: boolean;
  cityData: any;
  isLoadingCityData: boolean;
  isDateSelectorVisible: boolean;
  departDate: number;
  highSpeed: boolean;
};

const indexState: IndexStateType = {
  from: "北京",
  to: "上海",
  isCitySelectorVisible: false,
  currentSelectingLeftCity: false,
  cityData: null,
  isLoadingCityData: false,
  isDateSelectorVisible: false,
  departDate: Date.now(),
  highSpeed: false,
};

export const fetchCityData = createAsyncThunk(
  "/rest/cities",
  async (_, { dispatch }) => {
    fetch("http://localhost:8002/rest/cities")
      .then((res) => res.json())
      .then((cityData) => {
        dispatch(setCityData(cityData));
      });
  }
);

export const indexSlice = createSlice({
  name: "index",
  initialState: indexState,
  reducers: {
    setFrom(state: IndexStateType, from: PayloadAction<string>) {
      state.from = from.payload;
    },
    setTo(state: IndexStateType, from: PayloadAction<string>) {
      state.to = from.payload;
    },
    setIsLoadingCityData(state: IndexStateType, from: PayloadAction<boolean>) {
      state.isCitySelectorVisible = from.payload;
    },
    setCityData(state: IndexStateType, city: PayloadAction<any>) {
        console.log(city);
        
      state.cityData = city.payload;
    },
    toggleHighSpeed(state: IndexStateType) {
      state.highSpeed = !state.highSpeed;
    },
    showCitySelector(
      state: IndexStateType,
      currentSelectingLeftCity: PayloadAction<boolean>
    ) {
      state.isCitySelectorVisible = true;
      state.currentSelectingLeftCity = currentSelectingLeftCity.payload;
    },
    hideCitySelector(state: IndexStateType) {
      state.isCitySelectorVisible = false;
    },
    setSelectedCity(state: IndexStateType, city: PayloadAction<string>) {
      if (state.currentSelectingLeftCity) {
        state.from = city.payload;
      } else {
        state.to = city.payload;
      }
      state.isCitySelectorVisible = false;
    },
    showDateSelector(state: IndexStateType) {
      state.isDateSelectorVisible = true;
    },
    hideDateSelector(state: IndexStateType) {
      state.isDateSelectorVisible = false;
    },
    exchangeFromTo(state: IndexStateType) {
      const tmp = state.from;
      state.from = state.to;
      state.to = tmp;
    },
  },
});

export const {
  setFrom,
  setTo,
  setIsLoadingCityData,
  setCityData,
  toggleHighSpeed,
  showCitySelector,
  hideCitySelector,
  setSelectedCity,
  showDateSelector,
  hideDateSelector,
  exchangeFromTo,
} = indexSlice.actions;

export default indexSlice.reducer;
